package org.qiancizhan.Config;


import org.qiancizhan.Utils.ConfigUtil;
import org.qiancizhan.Utils.RowMapper;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;


public class MySQL {
    private static final String URL = ConfigUtil.get("db.url");
    private static final String USER = ConfigUtil.get("db.username");
    private static final String PASSWORD = ConfigUtil.get("db.password");

    private Connection conn = null;
    private static MySQL instance = null;

    public MySQL() {
        connect();
    }

    public static MySQL getInstance() {
        if (MySQL.instance == null) MySQL.instance = new MySQL();
        return MySQL.instance;
    }

    public void connect() {
        try {
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        } catch (Exception e) {
            throw new RuntimeException("数据库连接失败:", e);
        }
    }

    public Connection getConnection() {
        try {
            if (conn == null || conn.isClosed()) connect();
        } catch (SQLException e) {
            throw new RuntimeException("Connection is not valid", e);
        }
        return conn;
    }

    public <T> List<T> executeQuery(String sql, RowMapper<T> rowMapper) {
        try (Statement statement = getConnection().createStatement();
             ResultSet resultSet = statement.executeQuery(sql)) {

            List<T> list = new ArrayList<>();
            while (resultSet.next()) {
                T t = rowMapper.mapRow(resultSet);
                list.add(t);
            }
            return list;

        } catch (SQLException e) {
            throw new RuntimeException("查询出错", e);
        }
    }

    public int executeUpdate(String sql, Object... params) {
        try (PreparedStatement statement = getConnection().prepareStatement(sql)) {
            for (int i = 0; i < params.length; i++)
                statement.setObject(i + 1, params[i]);
            return statement.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新出错", e);
        }
    }

    public void close() {
        try {
            if (conn != null && !conn.isClosed()) {
                conn.close();
                System.out.println("MySQL连接断开");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}